package cn.vivi35.downloadprovider.app;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;


public abstract class DownloadContentObserver {

	private Cursor mDateSortedCursor;
	private MyContentObserver mContentObserver;
	private Context mContext;
	private DownloadManager mDownloadManager;


	public DownloadContentObserver(Context context, DownloadManager dm) {
		mContext = context;
		mContentObserver = new MyContentObserver(this);
		mDownloadManager = new DownloadManager(mContext.getContentResolver(), mContext.getPackageName());
		mDownloadManager.setAccessAllDownloads(true);
		DownloadManager.Query baseQuery = new DownloadManager.Query();
		mDateSortedCursor = mDownloadManager.query(baseQuery);
	}
	
	public void registerContentObserver() {
		mDateSortedCursor.registerContentObserver(mContentObserver);
	}
	

	public void unregisterContentObserver() {
		mDateSortedCursor.unregisterContentObserver(mContentObserver);
	}
	

	public abstract void onChange(Cursor cursor);

	private class MyContentObserver extends ContentObserver {
		DownloadContentObserver observer;


		public MyContentObserver(DownloadContentObserver observer) {
			super(new Handler());
			this.observer = observer;
		}


		@Override
		public void onChange(boolean selfChange) {
			observer.onChange(mDateSortedCursor);
		}
	}
}
